package com.spotmanger.project.modular.spotfile.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spotmanger.project.common.core.aop.annotation.LogAnnotation;
import com.spotmanger.project.common.core.utils.DataResult;
import com.spotmanger.project.common.core.utils.JacksonUtils;
import com.spotmanger.project.common.core.utils.ServletUtils;
import com.spotmanger.project.common.core.utils.StringUtils;
import com.spotmanger.project.common.core.utils.file.FileUtils;
import com.spotmanger.project.common.core.utils.text.Convert;
import com.spotmanger.project.core.entity.JsonResult;
import com.spotmanger.project.modular.spotfile.config.EasyfileConfig;
import com.spotmanger.project.modular.spotfile.entity.EasyfileChunk;
import com.spotmanger.project.modular.spotfile.entity.EasyfileEntity;
import com.spotmanger.project.modular.spotfile.service.IEasyfileService;
import com.spotmanger.project.modular.orgmanger.entity.SysDivisionEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.PathParam;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Easyfile文件存储管理服务
 *
 * @author leihao
 * @version 1.0
 * @date 2020年12月22日
 * @description
 */
@Controller
@RequestMapping("/spotfile")
public class SpotFileController {

    private static final Logger log = LoggerFactory.getLogger(SpotFileController.class);

    private String prefix = "spotfile";

    @Value("${spring.servlet.upload.file-path}")
    private String uploadFilePath;

    @Resource
    private EasyfileConfig easyfileConfig;

    @Resource
    private IEasyfileService easyfileService;

    @GetMapping("/index")
    public String spotfile() {
        return prefix + "/index.html";
    }

    @GetMapping("/upload")
    public String upload(ModelMap modelMap, @PathParam("tbbh") String tbbh) {
        modelMap.addAttribute("tbbh", tbbh);
        return prefix + "/upload.html";
    }


    @GetMapping("/list")
    @LogAnnotation(title = "文件操作", action = "获取图斑现场照片")
    @ResponseBody
    public DataResult list(@PathParam("tbbh") String tbbh) {
        Page page = new Page(1, 10);
        LambdaQueryWrapper<EasyfileEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EasyfileEntity::getTbbh, tbbh);
        IPage<SysDivisionEntity> iPage = easyfileService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }

//	/**
//	 * 获取所有上传文件配置
//	 * @return
//	 */
//	@GetMapping("/config")
//	@ResponseBody
//	public JsonResult config() {
//		return JsonResult.success(easyfileConfig);
//	}

    /**
     * 上传页面
     *
     * @return
     */
    @GetMapping("/upload/{business}")
    @RequiresPermissions("spotfile:file:upload")
    public String upload(@PathVariable("business") String business, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> allowConfig = easyfileConfig.getEasyfileConfigByBusiness(business);
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            JsonResult jsonResult = JsonResult.success(allowConfig);
            return ServletUtils.renderString(response, JacksonUtils.toJSONString(jsonResult));
        }

        modelMap.put("allowConfig", allowConfig);
        return prefix + "/upload";
    }

    /**
     * 上传
     *
     * @param file
     * @param easyfileChunk
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @RequiresPermissions("spotfile:file:upload")
    @ResponseBody
    public JsonResult upload(@RequestParam("file") MultipartFile file, EasyfileChunk easyfileChunk) throws Exception {
        easyfileChunk = easyfileService.easyfileUpload(file, easyfileChunk, uploadFilePath);
        if ((easyfileChunk.getChunk() + 1) == easyfileChunk.getChunks()) {//当最后一个分片上传成功后要执行文件合并
            EasyfileEntity easyfileEntity = easyfileService.easyfileMerge(easyfileChunk, uploadFilePath);
            if (StringUtils.isNull(easyfileEntity)) {
                easyfileService.removeEasyfileChunk(easyfileChunk);
                return JsonResult.error("文件合并失败", easyfileChunk);
            } else {
                return JsonResult.success(easyfileEntity);
            }
        }
        return JsonResult.success(easyfileChunk);
    }

    /**
     * 下载
     *
     * @param fileId
     * @param response
     * @param request
     */
    @GetMapping("/download/{fileId}")
    @RequiresPermissions("spotfile:file:download")
    @ResponseBody
    public void download(@PathVariable("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) {
        try {
            EasyfileEntity easyfileEntity = easyfileService.selectEasyfileEntityById(fileId);
            String filePath = uploadFilePath + File.separator + easyfileEntity.getFilePath();
            String fileName = FileUtils.setFileDownloadHeader(request, easyfileEntity.getOriginalName());
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 删除文件信息
     *
     * @param ids
     * @return
     */
    @RequiresPermissions("spotfile:file:delete")
    @PostMapping("/delete")
    @ResponseBody
    public JsonResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        if (StringUtils.isNotEmpty(ids)) {
            easyfileService.deleteEasyfileEntityByIds(Convert.toStrArray(ids));
        }
        return JsonResult.success();
    }

    /**
     * 预览文件（一般是图片和PDF，其他文件无法在浏览器中预览）
     *
     * @param id
     * @param response
     */
    @GetMapping("/view/{id}")
    public void view(@PathVariable("id") String id, HttpServletResponse response) {
        try {
            EasyfileEntity easyfileEntity = easyfileService.selectEasyfileEntityById(id);
            if (easyfileEntity != null) {
                String filePath = uploadFilePath + File.separator + easyfileEntity.getFilePath();
                FileUtils.writeBytes(filePath, response.getOutputStream());
            }
        } catch (IOException e) {
            log.error("预览文件失败", e);
        }
    }

}
